import {
  AbstractButton,
  AbstractVideo,
  C13BottomDock,
  C37GiftCertificateCard,
  Header,
  Icon,
  Layout,
  Paragraph,
  WithMargins,
} from "@/components";
import { useEffect, useRef, useState } from "react";
import { apiWithAuth, useAuth } from "@/store/authContext";
import { VideoProps, View } from "@tarojs/components";
import { useDidHide, useDidShow, useRouter } from "@tarojs/taro";
import { DateShape } from "@/data/shared/timeTypes";
import Taro from "@tarojs/taro";
import { navigateTo } from "@/utils/navigation";
import { error, alert } from "@/utils";
import style from "./index.module.scss";
import { useApplicationInfo } from "@/store/applicationDataContext";

// Local to here
const enum ApiEventMapping {
  Course = 0,
  Talk = 1,
  Exhibition = 2,
}

const giftCardVideoLink = `https://vod-qa.lecolevancleefarpels.cn/sv/491e4160-188dca705ae/491e4160-188dca705ae.mp4`;

const generateNavigationLink = (eventType: ApiEventMapping) => {
  switch (eventType) {
    case ApiEventMapping.Course:
      return "pages/course-detail/index?id=";
    case ApiEventMapping.Talk:
      return "pages/talk-detail/index?id=";
    case ApiEventMapping.Exhibition:
      return "pages/exhibition-detail/index?id=";
  }
};

type GiftCardDetailResponseShape = {
  id: number;
  cardId: number;
  cardNo: string;
  useAround: ApiEventMapping;
  name: string;
  faceValue: string;
  mainColor: string;
  secondaryColor: string;
  tertiaryColor: string;
  startTime: DateShape;
  endTime: DateShape;
  isGive: boolean;
  // usedTime: null; // in API response not in documentation
  giftCardRelevanceVoList: {
    id: number;
    name: string;
  }[];
};

export default function UserGiftCertificatesDetails() {
  const { dispatchAuthAction } = useAuth();
  const [giftedData, setGiftedData] = useState<{
    senderId: string;
    sender: string;
    receiver: string;
    message: string;
  } | null>(null);
  const { dispatch } = useApplicationInfo();
  const pageInstance = Taro.getCurrentInstance().page;
  const [textAnimationStarted, setTextAnimationStarted] =
    useState<boolean>(false);
  const [ctaAnimationStarted, setCtaAnimationStarted] =
    useState<boolean>(false);
  const [videoEnded, setVideoEnded] = useState<boolean>(false);
  const [videoLoading, setVideoLoading] = useState<boolean>(true);
  const [ctaText, setCtaText] = useState<string>("");
  const [disabled, setDisabled] = useState<boolean>(false);
  const [ctaFunction, setCtaFunction] = useState<() => void>(() => {});

  const { params } = useRouter();
  const { id, senderId } = params;

  const [giftCardDetails, setGiftCardDetails] =
    useState<null | GiftCardDetailResponseShape>(null);

  const hanleTimeUpdate = async (e: any) => {
    if (e.detail.currentTime >= 0.1 && videoLoading) {
      setVideoLoading(false);
    }
    if (e.detail.currentTime >= e.detail.duration - 0.3 && !videoEnded) {
      const giftingVideo = Taro.createVideoContext("gifting-video");
      giftingVideo.pause();
      setVideoEnded(true);
    }
    if (e.detail.currentTime >= 4 && !textAnimationStarted && pageInstance) {
      pageInstance.animate!(
        `.${style["gift-certificate-receive-text"]}`,
        [
          {
            opacity: 0,
          },
          {
            opacity: 1,
          },
        ],
        1000,
        () => {}
      );
      setTextAnimationStarted(true);
    }
    if (e.detail.currentTime >= 4.5 && !ctaAnimationStarted && pageInstance) {
      setCtaAnimationStarted(true);
      await apiWithAuth(
        `/user/card/info/claim?cardNo=${id}`,
        (res) => {
          const { data } = res;
          if (res.statusCode === 200) {
            if (data.code === 200) {
              if (data.data.userId === data.data.owner) {
                setDisabled(true);
                if (data.data.buyer === data.data.owner) {
                  setCtaText("礼品卡未领取");
                } else {
                  setCtaText("礼品卡已领取");
                }
              } else {
                if (data.data.buyer === data.data.owner) {
                  setCtaText("收下礼品卡");
                  setCtaFunction(() => handleReceive);
                } else {
                  setDisabled(true);
                  setCtaText("礼品卡已领取");
                }
              }
              pageInstance.animate!(
                `.${style["gift-certificate-receive-button"]}`,
                [
                  {
                    opacity: 0,
                  },
                  {
                    opacity: 1,
                  },
                ],
                1000,
                () => {}
              );
            } else {
              error(data.message);
            }
          }
        },
        { authDispatch: dispatchAuthAction, withoutLoading: true }
      );
    }
  };

  const handlePlay = () => {
    Taro.hideLoading();
  };

  const handleReceive = async () => {
    await apiWithAuth(
      `/user/getCard?cardNo=${id}&sendUser=${senderId}`,
      (res) => {
        const { data } = res;
        if (data.code === 200) {
          alert("领取成功");
          setCtaText("查看我的礼品卡");
          setCtaFunction(() => handleGotoListing);
        } else {
          error(data.message);
        }
      },
      {
        method: "POST",
        authDispatch: dispatchAuthAction,
      }
    );
  };

  const handleGotoListing = () => {
    navigateTo(`pages/user-gift-certificates/index`);
  };

  useDidShow(async () => {
    if (id) {
      if (params.senderId) {
        const { senderId, sender, receiver, message } = params;
        setGiftedData({
          senderId,
          sender: sender ? decodeURIComponent(sender) : "",
          receiver: receiver ? decodeURIComponent(receiver) : "",
          message: message ? decodeURIComponent(message) : "",
        });
      } else {
        return await apiWithAuth(
          `/user/card/info?id=${id}`,
          (res) => {
            if (res.statusCode === 200) {
              setGiftCardDetails(res.data.data as GiftCardDetailResponseShape);
            }
          },
          { authDispatch: dispatchAuthAction }
        );
      }
    } else {
      Taro.hideLoading();
      Taro.navigateBack();
    }
  });

  useEffect(() => {
    Taro.showLoading();
  }, []);

  return (
    <>
      <Layout>
        {giftedData ? (
          <View className={style["gift-certificate-receive"]}>
            <AbstractVideo
              id="gifting-video"
              className={style["gift-certificate-video"]}
              objectFit="contain"
              loop={false}
              onTimeUpdate={hanleTimeUpdate}
              onPlay={handlePlay}
              src={giftCardVideoLink}
            ></AbstractVideo>
            <View className={style["gift-certificate-receive-text"]}>
              <View className={style["gift-certificate-receive-title"]}>
                亲爱的{giftedData.receiver},
              </View>
              <View className={style["gift-certificate-receive-paragraph"]}>
                <View>你获赠了一张礼品卡。</View>
                <View>{giftedData.message}</View>
              </View>
              <View className={style["gift-certificate-receive-sign"]}>
                {giftedData.sender}
              </View>
            </View>

            <View className={style["gift-certificate-receive-button"]}>
              <AbstractButton
                color="white-opacity"
                disabled={disabled}
                onClick={ctaFunction}
              >
                {ctaText}
              </AbstractButton>
            </View>
            {videoLoading && (
              <View
                className={style["gift-certificate-receive-loading"]}
              ></View>
            )}
          </View>
        ) : (
          <>
            <View className={style["gift-certificate-details-wrapper"]}>
              <WithMargins>
                <Paragraph noSpacing>礼品卡信息</Paragraph>
                {/* <Header type={"heading-l"}>创意工作坊</Header> */}
                {giftCardDetails && (
                  <>
                    <View className={style["gift-card-spacing"]}>
                      <C37GiftCertificateCard
                        colorTheme={{
                          mainColor: giftCardDetails.mainColor,
                          upperTriangle: giftCardDetails.secondaryColor,
                          lowerTriangle: giftCardDetails.tertiaryColor,
                        }}
                        id={giftCardDetails.id}
                        title={giftCardDetails.name}
                        endTime={giftCardDetails.endTime}
                        showDetailLink={false}
                      />
                    </View>
                    <Paragraph size="small">可选课程</Paragraph>
                    {giftCardDetails.giftCardRelevanceVoList &&
                      giftCardDetails.giftCardRelevanceVoList.length &&
                      giftCardDetails.giftCardRelevanceVoList.map(
                        (usableEvent) => (
                          <View
                            key={usableEvent.id}
                            className={style["event-link"]}
                            onClick={() =>
                              navigateTo(
                                `${generateNavigationLink(
                                  giftCardDetails.useAround
                                )}${usableEvent.id}`
                              )
                            }
                          >
                            <Header type="heading-s">{usableEvent.name}</Header>
                            <Icon
                              type="GoToChevron"
                              className={style.chevron}
                            />
                          </View>
                        )
                      )}
                  </>
                )}
              </WithMargins>
            </View>
            <View className={style.dock}>
              <C13BottomDock
                onPrimaryClick={{
                  cb: giftCardDetails?.isGive
                    ? () => {
                        navigateTo(
                          `pages/user-gift-certificates-share-form/index?id=${giftCardDetails.cardNo!}`
                        );
                      }
                    : () => {},
                  disabled: giftCardDetails?.isGive ? false : true,
                  text: "赠送礼品卡",
                }}
                onSecondaryClick={null}
              />
            </View>
          </>
        )}
      </Layout>
    </>
  );
}
